String.prototype.firstUpperCase = function(){
    var str=this.toLowerCase();
    return str.replace(/\b(\w)(\w*)/g, function($0, $1, $2) {
        return $1.toUpperCase() + $2.toLowerCase();
    });
};
String.prototype.camelToUnderline=function () {
    return this.replace(/([A-Z])/g,"-$1").toLowerCase();
};
String.prototype.underlineToCamel=function () {
    var str=this.toLowerCase();
    return str.replace(/_(\w)/g, function(all, $1){
        return $1.toUpperCase();
    });
};
var CONTEXT_PATH="http://localhost:8088";

(function( window, document, undefined) {
	
	var diaoer={
		util:{
			isEnvProd:function () {
                return ENV_PROD===window.env;
            },
            httpGet: function (url) {
                var dtd = $.Deferred();
                $.ajax({
                    url: CONTEXT_PATH + url,
                    contentType: "application/json",
                    success: function (rt) {
                        dtd.resolve(rt);
                    }
                });
                return dtd.promise();
            },
            httpPost: function (url, params) {
                var dtd = $.Deferred();
                $.ajax({
                    url: CONTEXT_PATH + url,
                    type: 'POST',
                    data: JSON.stringify(params),
                    contentType: "application/json",
                    success: function (rt) {
                        dtd.resolve(rt);
                    }
                });
                return dtd.promise();
            },
            addDay: function (days) {
                var dayAgo = new Date(new Date() - days * 24 * 60 * 60 * 1000 * -1);// days天的日期
                return this.formatDate(dayAgo);
            },
            addMonth: function (months) {
                var dayAgo = new Date();
                dayAgo.setMonth(dayAgo.getMonth() + months);
                return this.formatDate(dayAgo);
            },
            removeItem:function (key) {
                if (!window.localStorage) {
                    return false;
                } else {
                    window.localStorage.removeItem(key);
                }
            },
            setItem: function (key, value) {
                if (!value) {
                    return false;
                }
                if (!window.localStorage) {
                    return false;
                } else {
                    if (this.isJson(value)) {
                        $.each(value, function (k, v) {
                            if (!v || v === 'null') {
                                delete value[k];
                            }
                        });
                    }
                    var storage = window.localStorage;
                    if (value) {
                        storage.setItem(key, JSON.stringify(value));
                    }
                }
            },
            getItem: function (key) {
                if (!window.localStorage) {
                    return false;
                } else {
                    var storage = window.localStorage;
                    var value = storage.getItem(key);
                    return value ? JSON.parse(value) : null;
                }

            },
            sleep: function sleep(numberMillis) {
                var now = new Date();
                var exitTime = now.getTime() + numberMillis;
                while (true) {
                    now = new Date();
                    if (now.getTime() > exitTime)
                        return;
                }
            },
            getQueryParamByName: function (name) {
                var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
                var r = window.location.search.substr(1).match(reg);
                if (r != null) return unescape(r[2]);
                return null;
            },
            isString: function isString(obj) { // 判断对象是否是字符串
                return Object.prototype.toString.call(obj) === "[object String]";
            },
            isJson: function (obj) {
                var isjson = typeof(obj) == "object" && Object.prototype.toString.call(obj).toLowerCase() == "[object object]" && !obj.length;
                return isjson;
            },
            isEnterKey: function (e) {
                var keyCode = window.event ? e.keyCode : e.which;
                return keyCode === 13;
            },
            nullToEmpty: function (value) {
                return value ? value : '';
            },
            addElement: function (name, value) {
                var ele = document.createElement("input");
                ele.value = value;
                ele.name = name;
                return ele;
            },
            addElementToForm: function (tempForm, preName, data) {
                if (this.isJson(data)) {
                    for (var name in data) {
                        if ($.isArray(data[name]) || this.isJson(data[name])) {
                            this.addElementToForm(tempForm, `${preName}.${name}`, data[name]);
                        } else {
                            var ele = this.addElement(`${preName}.${name}`, data[name]);
                            tempForm.appendChild(ele);
                        }
                    }
                } else {
                    var len = data.length;
                    for (var i = 0; i < len; i++) {
                        var params = data[i];
                        if (this.isJson(params)) {
                            for (var name in params) {
                                if ($.isArray(params[name])) {
                                    this.addElementToForm(tempForm, `${preName}[${i}].${name}`, params[name]);
                                } else if (eb.util.isJson(params[name])) {
                                    this.addElementToForm(tempForm, `${preName}.${name}`, params[name]);
                                } else {
                                    var ele = this.addElement(`${preName}[${i}].${name}`, params[name]);
                                    tempForm.appendChild(ele);
                                }
                            }
                        } else {
                            var ele = this.addElement(`${preName}[${i}]`, params);
                            tempForm.appendChild(ele);
                        }

                    }
                }

            },
            startWith: function (source, str) {
                var reg = new RegExp("^" + str);
                return reg.test(source);
            },
            endWith: function (source, str) {
                var reg = new RegExp(str + "$");
                return reg.test(source);
            },
            exceptionHandle: function (res) {
                if (res.status === 504) {
                    eb.ui.alert('服务请求超时！');
                } else {
                    eb.ui.alert('服务器繁忙，请稍后再试！')
                }
            },
            isEmail: function (str) {
                if (!str) {
                    return true;
                }
                var reg = /^([a-zA-Z0-9_-])+([-.-_A-Za-z0-9])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
                var emails = this.split(str);
                var isEmail = true;
                $.each(emails, function (i, email) {
                    isEmail = reg.test(email);
                    if (!isEmail) {
                        return false;
                    }
                });
                return isEmail;
            },
            isTrue: function (source) {
                return (/^true$/i).test(source);
            },
            httpProcessResult: function (res) {
                if (res.status === 200) {
                    var rs = res.data;
                    if (rs.code !== 200) {
                        eb.ui.alert("信息提示", rs.message && '未知系统异常'!==rs.message  ? rs.message : DEFAULT_ERROR_MSG);
                    } else {
                        return rs.data;
                    }
                } else {
                    eb.ui.alert("信息提示", DEFAULT_ERROR_MSG);
                }
                return null;
            },
            // 这个方法仅DTS_EB_SERVICE使用
            submitFormByGet: function (url, params) {
                this.submitForm(DTS_EB_SERVICE + url, params);
            },
            openSelfWindow: function (url, params) {
                var tempForm = document.createElement("form");
                tempForm.action = BASE_URL + url;
                tempForm.target = "_self";
                tempForm.method = 'get';
                tempForm.style.display = "none";
                if (params) {
                    for (var name in params) {
                        if ($.isArray(params[name]) || $this.isJson(params[name])) {
                            $this.addElementToForm(tempForm, name, params[name]);
                        } else {
                            var ele = $this.addElement(name, params[name]);
                            tempForm.appendChild(ele);
                        }
                    }
                }
                document.body.appendChild(tempForm);
                tempForm.submit();
            },
            processUrl: function (url, isAuth) {
                if (url.indexOf(DTS_EB_SERVICE) < 0) {
                    if (isAuth !== false) {
                        if (url.indexOf(EB_AUTH) < 0) {
                            url = EB_AUTH + url;
                        }
                    }
                }
                return url;
            },
            openLink: function (url, params) {
                url = this.processUrl(url, params.isAuth);
                if (params) {
                    delete params.isAuth;
                }
                let paramStr = $.param(params);
                location.href = `${CONTEXT_PATH}${url}?${paramStr}`;
            },
            openPostWindow: function (url, params, isNewWin = true, target = '_self') {
                this.submitForm(url, params, 'post', isNewWin, target);
            },
            submitForm: function (url, params, method = 'get', isNewWin = false, target = '_self') {
                url = this.processUrl(url, params ? params.isAuth : null);
                if (params) {
                    delete params.isAuth;
                }
                var $this = this;
                var tempForm = document.createElement("form");
                tempForm.action = CONTEXT_PATH + url;
                tempForm.target = target;
                tempForm.method = method;
                tempForm.style.display = "none";
                if (params) {
                    for (var name in params) {
                        if ($.isArray(params[name]) || $this.isJson(params[name])) {
                            $this.addElementToForm(tempForm, name, params[name]);
                        } else {
                            var ele = $this.addElement(name, params[name]);
                            tempForm.appendChild(ele);
                        }
                    }
                }
                document.body.appendChild(tempForm);
                tempForm.submit();
            },
            selectPageProcessResult: function (rt) {
                if (!rt || rt.code !== 200) {
                    return {list: null, totalRow: 0};
                } else if (typeof (rt.data.total) === 'undefined') {
                    let list = rt.data;
                    if (this.rebirthKey) {
                        for (let i = 0; i < rt.data.length; i++) {
                            list[i]['text'] = list[i][this.rebirthKey];
                        }
                    }

                    return {
                        list: list,
                        totalRow: rt.data.length
                    };
                } else {
                    let list = rt.data.list;
                    if (this.rebirthKey) {
                        for (let i = 0; i < list.length; i++) {
                            list[i]['text'] = list[i][this.rebirthKey];
                        }
                    }
                    return {
                        list: list,
                        totalRow: rt.data.total
                    };
                }
            },
            strReverse: function (str) {
                return str == null ? str : str.split('').reverse().join('');
            },
            getSystemDate:function (fmt) {
                return this.formatDate(window.systemDate?new Date(window.systemDate):new Date(),fmt);
            },
            formatDate: function (date, fmt = SHORT_DATE_PATTERN) {
                var o = {
                    "M+": date.getMonth() + 1, // 月份
                    "d+": date.getDate(), // 日
                    "h+": date.getHours(), // 小时
                    "m+": date.getMinutes(), // 分
                    "s+": date.getSeconds(), // 秒
                    "q+": Math.floor((date.getMonth() + 3) / 3), // 季度
                    "S": date.getMilliseconds() // 毫秒
                };
                if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
                for (var k in o)
                    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                return fmt;
            },
            getItemValue: function (item, field) {
                var value = item;
                if (typeof field !== 'string' || item.hasOwnProperty(field)) {
                    return item[field];
                }
                var props = field.split('.');
                for (var p in props) {
                    value = value && value[props[p]];
                }
                return value;
            },
            setItemValue: function (item, field, value) {
                if (typeof field !== 'string') {
                    return;
                }
                var sumItem = item;
                var props = field.split('.');
                for (var p in props) {
                    if (p == props.length - 1) {
                        sumItem[props[p]] = value;
                    } else {
                        if (!sumItem[props[p]]) {
                            sumItem[props[p]] = {};
                        }
                        sumItem = sumItem[props[p]];

                    }
                }
            },
            clearItemValue: function (item, field) {
                if (typeof field !== 'string') {
                    return;
                }
                var sumItem = item;
                var props = field.split('.');
                for (var p in props) {
                    if (p == props.length - 1) {
                        delete sumItem[props[p]];
                    } else {
                        if (!sumItem[props[p]]) {
                            sumItem[props[p]] = {};
                        }
                        sumItem = sumItem[props[p]];

                    }
                }
            },
            setBroItemValue: function (item, field, bro, value) {
                if (typeof field !== 'string') {
                    return;
                }
                var sumItem = item;
                var props = field.split('.');
                for (var p in props) {
                    if (p == props.length - 2) {
                        if (!value && sumItem[props[p]]) {
                            delete sumItem[props[p]][bro]
                        } else if (sumItem[props[p]]) {
                            sumItem[props[p]][bro] = value;
                        }
                    } else {
                        if (!sumItem[props[p]]) {
                            sumItem[props[p]] = {};
                        }
                        sumItem = sumItem[props[p]];
                    }
                }
            },
            clearItem: function clearItem(item, field) {
                if (typeof field !== 'string') {
                    return;
                }
                var sumItem = item;
                var props = field.split('.');
                for (var p in props) {
                    if (p == props.length - 1) {
                        delete sumItem[props[p]];
                    } else {
                        if (!sumItem[props[p]]) {
                            sumItem[props[p]] = {};
                        }
                        sumItem = sumItem[props[p]];
                    }
                }
            },
            isExists: function (source, str) {
                return source === null ? false : source.indexOf(str) !== -1;
            },
            isNumber:function (value) {
                if(value===null){
                    return false;
                }
                var patrn = /^(-)?\d+(\.\d+)?$/;
                if (patrn.exec(value)) {
                    return true;
                }
                return false;
            },
            remove: function (arr, value) {
                $.each(arr, function (index, ele) {
                    if (ele === value) {
                        arr.splice(index, 1);
                        return false;
                    }
                });
            },
            removeObject: function (arr, object, key) {
                $.each(arr, function (index, ele) {
                    if (ele[key] === object[key]) {
                        arr.splice(index, 1);
                        return false;
                    }
                });
            },
            removeObjectByValue: function (arr, values, key) {
                if (!arr) {
                    return;
                }
                for (var i = 0; i < arr.length;) {
                    var ele = arr[i];
                    if (values instanceof Array) {
                        if ($.inArray(ele[key], values) >= 0) {
                            arr.splice(i, 1);
                            continue;
                        }
                    } else {
                        if (ele[key] === values) {
                            arr.splice(i, 1);
                            continue;
                        }
                    }
                    i++;
                }
            },
            split: function (str) {
                return str ? str.split(/[\n\s,，;；]/g) : str;
            },
            formatName:function (name,startIndex) {
                if(!name){
                    return name;
                }
                if(typeof startIndex === "undefined"){
                    startIndex=1;
                }
                startIndex=Math.min(name.length,startIndex);
                let newStr;
                if (name.length >0) {
                    let char = '';
                    for (let i = 0, len = name.length - startIndex; i < len; i++) {
                        char += '*';
                    }
                    newStr = name.substr(0, startIndex) + char ;
                } else {
                    newStr = name;
                }
                return newStr;
            },
            // 比较不包含Array,RegExp,Function的Obejct。
            isObjectEqual: function (a, b) {
                if (typeof a === 'object' && typeof b === 'object') {
                    if (!(a instanceof Array) && !(b instanceof Array) && !(a instanceof RegExp) && !(b instanceof RegExp) && !(a instanceof Function) && !(b instanceof Function)) {
                        var aProps = Object.getOwnPropertyNames(a);
                        var bProps = Object.getOwnPropertyNames(b);
                        if (aProps.length != bProps.length) {
                            return false;
                        }
                        for (let i = 0; i < aProps.length; i++) {
                            let propName = aProps[i];
                            if (a[propName] !== b[propName]) {
                                if (typeof a[propName] === 'object' && typeof b[propName] === 'object') {
                                    if (!this.isObjectEqual(a[propName], b[propName])) {
                                        return false;
                                    }
                                } else {
                                    return false;
                                }
                            }
                        }
                    } else {
                        return false;
                    }
                    return true;
                } else {
                    return false;
                }
	        }
		}
	}
	window.diaoer=diaoer
}(window, document));